package com.efounder.chat.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.ChineseCharacterUtils;
import com.efounder.mobilecomps.contacts.User;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 好友数据库管理
 *
 * @author yqs
 */
public class FriendsDBManager {
    private SQLiteDatabase db;
    private int loginUserId;

    public FriendsDBManager() {
        this.loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID, "0")).intValue();

        this.db = GetDBHelper.getInstance().getDb();
    }

//	/**
//	 * 插入单个好友
//	 *
//	 * @param user
//	 * @return
//	 */
//	public long insertFriend(User user) {
//		ContentValues values = getFriendsContentValues(user);
//		return this.db.insert("Friends", null, values);
//
//	}

    /**
     * 插入或更新单个好友
     *
     * @param user
     * @return
     */
    public long insertOrReplce(User user) {
        user.setLoginUserId(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        ContentValues values = getFriendsContentValues(user);
        return this.db.insertWithOnConflict("Friends", null, values,
                SQLiteDatabase.CONFLICT_REPLACE);

    }

    /**
     * 插入或更新多个好友
     *
     * @param users
     */
    public void insertOrReplce(List<User> users) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = users.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            insertOrReplce(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    /**
     * 通过id查询好友
     *
     * @param id
     * @return
     */
    public User queryById(int id) {
        String sql = "select * from friends,user where friends.userId=" + id
                + " and friends.loginUserId =" + loginUserId + " and user.userid =" + id + " and friends.enable = 1;";
        List<?> list = query(sql);
        return ((list.size() == 0) ? null : (User) list.get(0));

    }

    /**
     * 查询是否是好友
     *
     * @param id
     * @return
     */
    public boolean queryIsFriend(int id) {
        String sql = "select * from friends where friends.userId =? and friends.loginUserId =?" +
                " and friends.enable = ?";
        Cursor cursor = this.db.rawQuery(sql, new String[]{id + "", loginUserId + "", 1 + ""});
        int i = 0;
        while (cursor.moveToNext()) {
            i += 1;
        }
        cursor.close();
        if (i > 0) {
            return true;
        }
        return false;
    }


    /**
     * 查询所有好友
     *
     * @return
     */
    public List<User> queryAllFriends() {
        String sql = "select * from friends,user where friends.enable =1 "
                + " and friends.userid = user.userid  and user.type = 0 and friends.loginUserId =" + loginUserId;
        List<User> list = query(sql);
        return list;

    }

    /**
     * 根据关键字查询好友
     * 现在已经改成了查询用户表
     *
     * @param keyword 关键字
     * @return
     */
    public List<User> queryFriendsByKeyword(String keyword) {
        keyword = "%" + keyword + "%";
//        String sql = "select a.userid as fuserid,a.istop,a.isbother,a.remark,a.isImportent,a.loginuserid,b.* from friends as a " +
//                " left join User as b on a.userid = b.userId " +
//                " where a.enable=1 and b.type=0 and( a.remark like ? or b.nickname like ? or b.userId like ?" +
//                "or a.remark_py_initial like ? or a.remark_py_quanpin like ? or b.nickname_py_initial like ?" +
//                "or b.nickname_py_quanpin like ?)";
        String sql = "select a.*,b.remark from User as a " +
                " left join Friends as b on a.userid = b.userId " +
                " where   a.type=0 and( b.remark like ? or a.nickname like ? or a.userId like ? " +
                "or b.remark_py_initial like ? or b.remark_py_quanpin like ? or a.nickname_py_initial like ?" +
                "or a.nickname_py_quanpin like ?)";
        List<User> list = query(sql, new String[]{keyword, keyword, keyword, keyword, keyword, keyword, keyword});
        return list;

    }

    /**
     * 查询所有自己关注的应用号
     *
     * @return
     */
    public List<User> queryAllOfficialNumber() {
        String sql = "select * from friends,user where friends.enable =1 "
                + " and friends.userid = user.userid and user.type = 1 and friends.loginUserId =" + loginUserId;
        List<User> list = query(sql);
        return list;

    }

    /**
     * 更新好友置顶或者免打扰状态
     *
     * @param user
     * @return
     */
    public int updateIsTopOrBother(User user) {
        user.setLoginUserId(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        ContentValues values = getFriendsContentValues2(user);
        String whereClause = "userId=? and loginUserId = ?";
        String[] whereArgs = {String.valueOf(user.getId()),
                String.valueOf(user.getLoginUserId())};
        return this.db.update("friends", values, whereClause, whereArgs);
    }

    /**
     * 更新好友(list)
     *
     * @param list
     * @return
     */
    public void update(List<User> list) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = list.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            user.setLoginUserId(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));
            updateIsTopOrBother(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    /**
     * 删除好友（单个）
     *
     * @param user
     * @return
     */
    public void delete(User user) {
        this.delete(user.getId());
    }

    /**
     * 删除好友（单个）
     *
     * @param userId
     * @return
     */
    public void delete(int userId) {

        this.db.execSQL("update Friends set enable=0 where userId =" + userId
                + " and loginUserId =" + loginUserId + ";");
    }

    /**
     * 删除好友（多个）
     *
     * @param userList
     */
    public void delete(List<User> userList) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = userList.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            delete(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    public List<User> query(String sql) {
        return query(sql, null);
    }

    public List<User> query(String sql, String[] selectionArgs) {
        List<User> list = new ArrayList<User>();
        Cursor cursor = this.db.rawQuery(sql, selectionArgs);
        while (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(cursor.getColumnIndex("userId")));

//            user.setReMark(cursor.getString(cursor.getColumnIndex("remark")));
//            user.setIsBother(cursor.getInt(cursor.getColumnIndex("isBother")) == 1 ? true
//                    : false);
//            user.setIsTop(cursor.getInt(cursor.getColumnIndex("isTop")) == 1 ? true
//                    : false);


            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setNickName(cursor.getString(cursor.getColumnIndex("nickName")));
            user.setSex(cursor.getString(cursor.getColumnIndex("sex")));
            user.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            user.setMobilePhone(cursor.getString(cursor.getColumnIndex("mobilephone")));
            user.setAvatar(cursor.getString(cursor.getColumnIndex("avatar")));
            user.setSigNature(cursor.getString(cursor.getColumnIndex("sigNature")));
            user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
            user.setDeptId(cursor.getInt(cursor.getColumnIndex("deptId")));
            user.setType(cursor.getInt(cursor.getColumnIndex("type")));
            user.setPlanet(cursor.getColumnIndex("planet") == -1 ? "" :
                    cursor.getString(cursor.getColumnIndex("planet")));

            if (cursor.getColumnIndex("isImportent") != -1) {
                user.setIsImportantContacts(cursor.getInt(cursor.getColumnIndex("isImportent")) == 1 ? true : false);
            }
            if (cursor.getColumnIndex("loginUserId") != -1) {
                user.setLoginUserId(cursor.getInt(cursor.getColumnIndex("loginUserId")));
            }
            if (cursor.getColumnIndex("remark") != -1) {
                user.setReMark(cursor.getString(cursor.getColumnIndex("remark")));
            }
            if (cursor.getColumnIndex("isBother") != -1) {
                user.setIsBother(cursor.getInt(cursor.getColumnIndex("isBother")) == 1 ? true : false);
            }
            if (cursor.getColumnIndex("isTop") != -1) {
                user.setIsTop(cursor.getInt(cursor.getColumnIndex("isTop")) == 1 ? true : false);
            }

            String publicKey = cursor.getString(cursor.getColumnIndex("publicKey"));
            if (publicKey == null || "".equals(publicKey)) {
                user.setPublicKey(null);
            } else {
                user.setPublicKey(publicKey);
            }
            String walletAddress = cursor.getString(cursor.getColumnIndex("walletAddress"));
            if (walletAddress == null || "".equals(walletAddress)) {
                user.setWalletAddress(null);
            } else {
                user.setWalletAddress(walletAddress);
            }

            String rsaPublicKey = cursor.getString(cursor.getColumnIndex("RSAPublicKey"));
            if (rsaPublicKey == null || "".equals(rsaPublicKey)) {
                user.setRSAPublicKey(null);
            } else {
                user.setRSAPublicKey(rsaPublicKey);
            }
            String wechatQrUrl = cursor.getString(cursor.getColumnIndex("wechatQrUrl"));
            String zhifubaoQrUrl = cursor.getString(cursor.getColumnIndex("zhifubaoQrUrl"));
            user.setWeixinQrUrl((wechatQrUrl == null || "".equals(wechatQrUrl)) ? null : wechatQrUrl);
            user.setZhifubaoQrUrl((zhifubaoQrUrl == null || "".equals(zhifubaoQrUrl)) ? null : zhifubaoQrUrl);
            user.setAllowStrangerChat(cursor.getInt(cursor.getColumnIndex("stranger_chat")) == 1);

            if (user.getNickName() == null || user.getNickName().equals("")) {
                user.setNickName("ID" + String.valueOf(user.getId()));
            }
            list.add(user);
        }

        cursor.close();
        return list;
    }

    private ContentValues getFriendsContentValues(User user) {
        ContentValues values = new ContentValues();
        values.put("userId", user.getId());
        values.put("loginUserId", user.getLoginUserId());
        values.put("remark", user.getReMark());
        values.put("remark_py_initial", ChineseCharacterUtils.getJianPin(user.getReMark()));
        values.put("remark_py_quanpin", ChineseCharacterUtils.getQuanPin(user.getReMark()));
        values.put("isBother", user.getIsBother() == true ? 1 : 0);
        values.put("isTop", user.getIsTop() == true ? 1 : 0);
        values.put("isImportent",
                user.getIsImportantContacts() == true ? 1 : 0);
        values.put("enable", 1);
        return values;
    }

    private ContentValues getFriendsContentValues2(User user) {
        ContentValues values = new ContentValues();
        values.put("userId", user.getId());
        values.put("loginUserId", user.getLoginUserId());
        values.put("remark", user.getReMark());
        values.put("remark_py_initial", ChineseCharacterUtils.getJianPin(user.getReMark()));
        values.put("remark_py_quanpin", ChineseCharacterUtils.getQuanPin(user.getReMark()));
        values.put("isBother", user.getIsBother() == true ? 1 : 0);
        values.put("isTop", user.getIsTop() == true ? 1 : 0);
        values.put("isImportent",
                user.getIsImportantContacts() == true ? 1 : 0);
        values.put("enable", 1);
        return values;
    }

    /**
     * 关闭数据库
     */
    public void close() {
        this.db.close();
    }
}


